import 'dart:math' as math;

import 'package:flutter/material.dart';
import '../../uikit.dart';
import '../../utils/image_util/image_util.dart';

///图片加载中占位图
class ImageLoadingWidget extends StatelessWidget {
  const ImageLoadingWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(color: const Color(0xFFEDEDED));
  }
}

///图片加载失败占位图
class ImageLoadErrorWidget extends StatefulWidget {
  const ImageLoadErrorWidget({Key? key, this.width, this.height}) : super(key: key);

  ///下面两个值可能为空
  final double? width;
  final double? height;

  @override
  State<StatefulWidget> createState() {
    return ImageLoadErrorWidgetState();
  }
}

class ImageLoadErrorWidgetState extends State<ImageLoadErrorWidget> {
  ///以宽度为基准，图片占parent宽度的比例
  /// * 调大了此值，否则边长太小，会导致图形无法显示
  final double ratio = 0.5;

  double? imgWidth;
  double? imgHeight;

  @override
  void initState() {
    super.initState();
    if (widget.width == null) {
      WidgetsBinding.instance!.addPostFrameCallback((Duration timeStamp) {
        Future<dynamic>.delayed(const Duration(milliseconds: 16 * 4)).then((dynamic value) {
          if (!mounted) {
            return;
          }
          final RenderBox rb = context.findRenderObject() as RenderBox;
          imgWidth = rb.paintBounds.width;
          imgHeight = rb.paintBounds.height;
          setState(() {});
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.width != null && widget.height != null) {
      return Container(
        color: const Color(0xfff7f7f7),
        padding: EdgeInsets.all(widget.width! * ratio * ratio),
        width: widget.width,
        height: widget.height,
        child: ImageUtil.loadAssetImage(
          "lib/assets/state/img_loading_error.webp",
          package: RikiUikit.PACKAGE,
          width: math.min(widget.width!, widget.height!) * ratio,
          fit: BoxFit.scaleDown,
        ),
      );
    } else {
      if (imgWidth != null) {
        return Container(
          color: const Color(0xfff7f7f7),
          //padding: EdgeInsets.all(math.min(imgWidth, imgHeight) * (1 - ratio)),
          width: imgWidth,
          height: imgHeight,
          alignment: Alignment.center,
          child: ImageUtil.loadAssetImage(
            //R.libAssetsStateImgLoadingError,
            "lib/assets/state/img_loading_error.webp",
            package: RikiUikit.PACKAGE,
            width: math.min(imgWidth!, imgHeight!) * ratio,
            fit: BoxFit.scaleDown,
          ),
        );
      } else {
        return Container(
          color: const Color(0xfff7f7f7),
        );
      }
    }
  }
}
